package com.example.nna.voz;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.nna.main.R;
import com.example.nna.quickaction.ActionItem;
import com.example.nna.quickaction.QuickAction;
import com.example.nna.util.Subscribe;
import com.example.nna.util.UserInfo;

public class page3 extends Activity{
	private ListView mMainList;
	private static listViewCustom3 adapter;
	private Parser3 mParser;
	private Activity mActivity;
	private ProgressDialog progressDialog;
	private TextView m_TextLogin;
	private TextView m_Detail;
	private Context mContext;
	
	private String mUrl;
	private ArrayList<taskLoadImage> taskLoadImg;
	private int index;
	private PaserTask mTask;
	private UserInfo mUser;
	private String mForums;
	private String mTextReply;
	
	private int stateConenct;
	private AlertDialog.Builder alert;
	private View textEntryView;
	private LayoutInflater factory;
	private EditText edit1 ;
	private EditText edit2 ;
	private TextView text1 ;
	private TextView text2 ;
	private Integer pos;
	private Subscribe mSubscribe;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.page3);
		mSubscribe = new Subscribe(this);
		mMainList = (ListView)findViewById(R.id.page3);
		m_Detail = (TextView)findViewById(R.id.Page3Detail);
		m_TextLogin = (TextView)findViewById(R.id.Page3Login);

		mActivity = this;
		mContext = this;
		mUser = new UserInfo();
		taskLoadImg = new ArrayList<taskLoadImage>();
		mHandler.obtainMessage(Voz.MSG_PAGE3,mUrl).sendToTarget();
		progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);
        progressDialog.setMessage("Loading data......");
		mUrl = getIntent().getExtras().getString("url");
		mForums = getIntent().getExtras().getString("forum");
		mActivity.setTitle(mForums);
		index = 0;
		mMainList.setClickable(true);
		mMainList.setOnItemClickListener(mMainListClick);
		m_TextLogin.setOnClickListener(mLoginClick);
	}
	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		// TODO Auto-generated method stub
//		if(mUser.isLogin()){
//    		menu.findItem(R.id.menu_subscribe).setVisible(true);
//    		menu.findItem(R.id.menu_favourite).setVisible(true);
//    	}else{
//    		menu.findItem(R.id.menu_subscribe).setVisible(false);
//    		menu.findItem(R.id.menu_favourite).setVisible(false);
//    	}
//		if(mParser.Subscribe()){
//			Log.d("nna","true Un");
//			menu.findItem(R.id.menu_subscribe).setTitle("UnSubscribe");
//		}else{
//			Log.d("nna","true Su");
//			menu.findItem(R.id.menu_subscribe).setTitle("Subscribe");
//		}
		return super.onMenuOpened(featureId, menu);
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_parser_html, menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
     	switch (item.getItemId()) {
//     	case R.id.menu_subscribe:
//     		new PaserTask().execute(Voz.PASER_SUBSCRIBE);
//     		return true;
     	case R.id.menu_settings:
	        LayoutInflater factory2 = LayoutInflater.from(mContext);
		    View textEntryView2 = factory2.inflate(R.layout.alertsetting, null); 
		    CheckBox checkbox = (CheckBox)textEntryView2.findViewById(R.id.checkBox1);
		    
		    final Spinner spinner2 = (Spinner)textEntryView2.findViewById(R.id.setting_spinner2);
			List<String> list = new ArrayList<String>();
			list.add("1");
			list.add("5");
			list.add("10");
			list.add("15");
			list.add("30");
			ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(mContext,
				android.R.layout.simple_spinner_item, list);
			dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinner2.setAdapter(dataAdapter);
			spinner2.setSelection(Voz.mNotifTimerSelection);
		    spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {
	
				@Override
				public void onItemSelected(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					Voz.mNotifTimer = Integer.parseInt(arg0.getItemAtPosition(arg2).toString());
					Voz.mNotifTimerSelection = arg2;
				}
	
				@Override
				public void onNothingSelected(AdapterView<?> arg0) {
					// TODO Auto-generated method stub
					
				}
			});
		    
		    if(Voz.mNotifEnable) checkbox.setChecked(true);
		    else 	checkbox.setChecked(false);
		    if(checkbox.isChecked()) Voz.mNotifEnable = true;
		    else Voz.mNotifEnable = false;
		    Builder alert2 = new AlertDialog.Builder(mContext);
		    alert2.setView(textEntryView2);
		    alert2.setTitle("Setting");
		    alert2.show();
	        return true;
//     	case R.id.menu_favourite:
//  			Intent i = new Intent(mContext,pageUserCP.class );
//			startActivity(i);
//        	return true;  
     	case R.id.menu_font:
        	LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    	    View layout = inflater.inflate(R.layout.seekbar, null);
    	    AlertDialog.Builder builder = new AlertDialog.Builder(this).setView(layout);
    	    AlertDialog alertDialog = builder.create();
    	    alertDialog.show();
    	    SeekBar sb = (SeekBar)layout.findViewById(R.id.seek);
    	    sb.setMax(30);
    	    sb.setProgress((int)(30*(Voz.mTextSize-Voz.FONTSCALE_MIN)/(Voz.FONTSCALE_MAX-Voz.FONTSCALE_MIN)));
    	    sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
    	        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
    	            //Do something here with new value
    	        	Voz.mTextSize = (float)((Voz.FONTSCALE_MAX-Voz.FONTSCALE_MIN)/(30-0)*(progress) + Voz.FONTSCALE_MIN);
      	        	adapter.setSize(Voz.mTextSize);
    	        	adapter.notifyDataSetChanged();
    	        }
				@Override
				public void onStartTrackingTouch(SeekBar arg0) {
					// TODO Auto-generated method stub

				}
				@Override
				public void onStopTrackingTouch(SeekBar arg0) {
					// TODO Auto-generated method stub
				}
    	    });
            return true;
     	default:
     		return super.onOptionsItemSelected(item);
     	}
     

	}

	public final Handler mHandler = new Handler(){
	    	@Override
	    	public void handleMessage(Message msg) {
	    		 switch (msg.what) {
	    		 case Voz.MSG_CLICKMUTILQUOTE:
			     		if(mUser.isLogin() == true){
			     			if(mParser.getContains((Integer)msg.obj).isMultiQuote()){ 
				     			mParser.getContains((Integer)msg.obj).setMultiQuote(false);
				     			String temp =mUser.cookies().get("vbulletin_multiquote").replace(
				     								mParser.getContains((Integer)msg.obj).Id(), "");
				     			if(temp.contains("%2C") && temp.subSequence(0, 3).equals("%2C"))
				     				temp = temp.substring(3, temp.length());
				     			if(temp.contains("%2C")&& temp.subSequence(temp.length()-3, temp.length()).equals("%2C"))
				     				temp = temp.substring(0, temp.length()-3);
				     			if(temp.contains("%2C%2C"))
				     				temp = temp.replace("%2C%2C", "%2C");
				     			mUser.cookies().put("vbulletin_multiquote",temp);
				     		}else{ 
				     			mParser.getContains((Integer)msg.obj).setMultiQuote(true);
				     			if(mUser.cookies().containsKey("vbulletin_multiquote") != true){
					     			mUser.cookies().put("vbulletin_multiquote",
					     					mParser.getContains((Integer)msg.obj).Id());
					     		}else{
					     			mUser.cookies().put("vbulletin_multiquote",
					     							mUser.cookies().get("vbulletin_multiquote")+"%2C"+
					     							mParser.getContains((Integer)msg.obj).Id());		
					     		}
				     		}
				     		adapter.notifyDataSetChanged();
				     		Log.d("nna","multiquote:"+ mUser.cookies().get("vbulletin_multiquote"));
			     		}else{
			     			Toast.makeText(mContext, "Please Login", Toast.LENGTH_SHORT).show();
			     		}
			     		
		     			break;
	    		 case Voz.MSG_ALERTCOMMENT:
	    			 alert_comment((Integer)msg.obj);
	    			 break;
	    		 case Voz.MSG_GOTO:
	    			 switch ((Integer)msg.obj) {
						case 0:	GotoClick();break;
						case 1:	FirstClick();break;
						case 2:	PrevClick(); break;
						case 3:	NextClick();break;
						case 4:	LastClick();break;
						default:break;
						}
	    				 
	    			 break;
	    		 case Voz.MSG_PAGE3:
	    		    mParser = new Parser3(mUrl);
	  		        adapter = new listViewCustom3(mActivity,mHandler,mParser.getContains());
	  		        mMainList.setAdapter(adapter);
	  		        mTask = new PaserTask();
	  		        mTask.execute(Voz.PASER_PASER);
	    			 break;
	    	
	    		 case Voz.MSG_LOGIN:
	    		    mTask = new PaserTask();
	 		        mTask.execute(Voz.PASER_LOGIN);
	      			break;
		     	 case Voz.MSG_LOGOUT:
	     			mTask = new PaserTask();
	  		        mTask.execute(Voz.PASER_LOGOUT);
	     			break;
		     	 case Voz.MSG_QUICKREPLY:
	     			mTask = new PaserTask();
	  		        mTask.execute(Voz.PASER_QUICKREPLY);
	     			break;
		     	 case Voz.MSG_QUOTEREPLY:
	     			mTask = new PaserTask();
	  		        mTask.execute(Voz.PASER_QUOTEREPLY);
	     			break;
		     	case Voz.MSG_QUOTEGET:
		     		if(mUser.isLogin() == true){
		     			mTask = new PaserTask();
		  		        mTask.execute(Voz.PASER_QUOTEGET,(Integer)msg.obj,0);
		     		}else{
		     			Toast.makeText(mContext, "Please Login", Toast.LENGTH_SHORT).show();
		     		}
	     			break;
		     	case Voz.MSG_EDITGET:
		     		if(mUser.isLogin() == true){
		     			mTask = new PaserTask();
		  		        mTask.execute(Voz.PASER_QUOTEGET,(Integer)msg.obj,1);
		     		}else{
		     			Toast.makeText(mContext, "Please Login", Toast.LENGTH_SHORT).show();
		     		}
	     			break;
		     	case Voz.MSG_CLICKEDIT:
		     		if(mUser.isLogin() == true){
			     		Intent i = new Intent(mContext,  pageReply.class);
			     		Bundle extras = new Bundle();
		     			extras.putString("type","3");
		     			extras.putString("msg",(String)msg.obj);
		     			i.putExtras(extras);
		     			startActivityForResult(i, 3);
		     		}else{
		     			Toast.makeText(mContext, "Please Login", Toast.LENGTH_SHORT).show();
		     		}
	     			break;
		     	case Voz.MSG_CLICKREPLY:
		     		if(mUser.isLogin() == true){
			     		Intent i = new Intent(mContext,  pageReply.class);
			     		Bundle extras = new Bundle();
		     			extras.putString("type","0");
		     			extras.putString("msg","");
		     			i.putExtras(extras);
		     			startActivityForResult(i, 0);
		     		}else{
		     			Toast.makeText(mContext, "Please Login", Toast.LENGTH_SHORT).show();
		     		}
	     			break;	
		     	case Voz.MSG_CLICKQUOTE:
		     		if(mUser.isLogin() == true){
			     		Intent i = new Intent(mContext,  pageReply.class);
			     		Bundle extras = new Bundle();
		     			extras.putString("type","1");
		     			extras.putString("msg",(String)msg.obj);
		     			i.putExtras(extras);
		     			startActivityForResult(i, 1);
		     		}else{
		     			Toast.makeText(mContext, "Please Login", Toast.LENGTH_SHORT).show();
		     		}
		     		
	     			break;
		     	
		   	 case Voz.MSG_LIKEPAGE:
 				 Bundle extras = new Bundle();
 				 extras = new Bundle();
 				 extras.putString("url","http://vozforums.com/"+mSubscribe.getThread((Integer)msg.obj));
			 	 extras.putString("forum","test");
			 	 Intent i = new Intent(mContext,page3.class );
				 i.putExtras(extras);
				 startActivity(i);
    			 break;
	    		 }
	    	};
	 };

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == RESULT_OK){
			switch (requestCode) {
			case 0:
				mTextReply = data.getExtras().getString("msg");
				Toast.makeText(mContext, data.getExtras().getString("type")+
						";"+mTextReply, Toast.LENGTH_SHORT).show();
				//mHandler.obtainMessage(Voz.MSG_QUICKREPLY).sendToTarget();
				mTask = new PaserTask();
  		        mTask.execute(Voz.PASER_QUICKREPLY);
				break;
			case 1:
				mTextReply = data.getExtras().getString("msg");
				//mHandler.obtainMessage(Voz.MSG_QUOTEREPLY).sendToTarget();
				mTask = new PaserTask();
  		        mTask.execute(Voz.PASER_QUOTEREPLY);
				break;
			case 2:
				mTextReply = data.getExtras().getString("msg");
				//mHandler.obtainMessage(Voz.MSG_QUOTEREPLY).sendToTarget();
				mTask = new PaserTask();
  		        mTask.execute(Voz.PASER_QUOTEREPLY);
				break;
			case 3:
				mTextReply = data.getExtras().getString("msg");
				//mHandler.obtainMessage(Voz.MSG_EDITGET).sendToTarget();
				mTask = new PaserTask();
  		        mTask.execute(Voz.PASER_EDITREPLY);
				break;
			default:
				break;
			}
		}
	} 
	OnClickListener mCommentEdit = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			mHandler.obtainMessage(Voz.MSG_EDITGET, pos).sendToTarget();
		}
	};
	OnClickListener mCommentReply = new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mHandler.obtainMessage(Voz.MSG_CLICKREPLY, pos).sendToTarget();
			}
		};
	OnClickListener mCommentQuote = new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mHandler.obtainMessage(Voz.MSG_QUOTEGET, pos).sendToTarget();
			}
		};
	OnClickListener mCommentMultiQuote = new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mHandler.obtainMessage(Voz.MSG_CLICKMUTILQUOTE, pos).sendToTarget();
			}
		};
	void alert_comment(int pos){
		 	ActionItem addItem 		= new ActionItem(1, "Reply", getResources().getDrawable(R.drawable.replyquickreply));
			ActionItem acceptItem 	= new ActionItem(2, "Quote", getResources().getDrawable(R.drawable.replyquote));
	        ActionItem uploadItem 	= new ActionItem(3, "Multi", getResources().getDrawable(R.drawable.replymultiquote_off));
			
			final QuickAction mQuickAction 	= new QuickAction(this);
			mQuickAction.addActionItem(addItem);
			mQuickAction.addActionItem(acceptItem);
			mQuickAction.addActionItem(uploadItem);
//    	    if(mParser.getContains(pos).User().equals(mUser.User()))
//	    	imagEdit.setVisibility(View.VISIBLE);
//       	else imagEdit.setVisibility(View.GONE);
//       	 if(mParser.getContains(pos).isMultiQuote()){
//        		imagMulti.setImageResource(R.drawable.replymultiquote_on);
//        	}else{
//        		imagMulti.setImageResource(R.drawable.replymultiquote_off);
//       	 }
			
			mQuickAction.show(mMainList.getChildAt(pos));
			//setup the action item click listener
			mQuickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
				@Override
				public void onItemClick(QuickAction quickAction, int pos, int actionId) {
					
					if (actionId == 1) { //Add item selected
						mHandler.obtainMessage(Voz.MSG_CLICKREPLY, pos).sendToTarget();
					} else if(actionId == 2){
						mHandler.obtainMessage(Voz.MSG_QUOTEGET, pos).sendToTarget();
					}else if(actionId == 3){
						mHandler.obtainMessage(Voz.MSG_CLICKMUTILQUOTE, pos).sendToTarget();
					}		
				}
			});
	}
	OnItemClickListener mMainListClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, final View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			pos = arg2;
		 	ActionItem replyItem 	= new ActionItem(1, "Reply", getResources().getDrawable(R.drawable.replyquickreply));
			ActionItem quoteItem 	= new ActionItem(2, "Quote", getResources().getDrawable(R.drawable.replyquote));
			ActionItem multiItem;
	        ActionItem editItem 	= new ActionItem(4, "Edit", getResources().getDrawable(R.drawable.replyedit));
	        if(mParser.getContains(pos).isMultiQuote()){
	        	multiItem= new ActionItem(3, "Multi", 
	        			getResources().getDrawable(R.drawable.replymultiquote_on));
        	}else{
        		 multiItem 	= new ActionItem(3, "Multi",
        				getResources().getDrawable(R.drawable.replymultiquote_off));
        	}
	        final QuickAction mQuickAction 	= new QuickAction(mContext);
			mQuickAction.addActionItem(replyItem);
			mQuickAction.addActionItem(quoteItem);
			mQuickAction.addActionItem(multiItem);
    	    if(mParser.getContains(pos).User().equals(mUser.User()))
    	    	mQuickAction.addActionItem(editItem);
			mQuickAction.show(arg1);
			arg1.setBackgroundResource(R.color.red);
			mQuickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
				@Override
				public void onItemClick(QuickAction quickAction, int position, int actionId) {
					arg1.setBackgroundResource(R.color.white);
					if (actionId == 1) { //Add item selected
						mHandler.obtainMessage(Voz.MSG_CLICKREPLY, pos).sendToTarget();
					}else if(actionId == 2){
						mHandler.obtainMessage(Voz.MSG_QUOTEGET, pos).sendToTarget();
					}else if(actionId == 3){
						Log.d("nna",String.valueOf(pos));
						mHandler.obtainMessage(Voz.MSG_CLICKMUTILQUOTE, pos).sendToTarget();
					}		
				}
			});
			
			mQuickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
				
				@Override
				public void onDismiss() {
					arg1.setBackgroundResource(R.color.white);
					// TODO Auto-generated method stub
				}
			});
				
			
		}

	};

	private void NextClick(){
		for(int i=0;i<taskLoadImg.size();i++){
			taskLoadImg.get(i).ld.cancel(true);
		}
		mTask.cancel(true);
		
		if(mParser.Urlnext != null){
			mUrl = mParser.Urlnext;
			mHandler.obtainMessage(Voz.MSG_PAGE3).sendToTarget();
		}else{
			Toast.makeText(mActivity, "Cannot go to Next", Toast.LENGTH_LONG).show();
		}
	}
	
	private void PrevClick(){
		for(int i=0;i<taskLoadImg.size();i++){
			taskLoadImg.get(i).ld.cancel(true);
		}
		mTask.cancel(true);
		if(mParser.Urlprev != null){
			mUrl = mParser.Urlprev;
			mHandler.obtainMessage(Voz.MSG_PAGE3).sendToTarget();
		}else{
			Toast.makeText(mActivity, "Cannot go to Previous.", Toast.LENGTH_LONG).show();
		}
	}
	private void FirstClick(){
		for(int i=0;i<taskLoadImg.size();i++){
			taskLoadImg.get(i).ld.cancel(true);
		}
		mTask.cancel(true);
		if(mParser.Urlfirst!=null){
			mUrl = mParser.Urlfirst;
			mHandler.obtainMessage(Voz.MSG_PAGE3).sendToTarget();
		}else Toast.makeText(mActivity, "Cannot go to first! ", Toast.LENGTH_LONG).show();

	}
	private void GotoClick(){
		for(int i=0;i<taskLoadImg.size();i++){
			taskLoadImg.get(i).ld.cancel(true);
		}
		mTask.cancel(true);
		mHandler.obtainMessage(Voz.MSG_PAGE3).sendToTarget();
	}
	private void LastClick(){
		for(int i=0;i<taskLoadImg.size();i++){
			taskLoadImg.get(i).ld.cancel(true);
		}
		mTask.cancel(true);
		
		if(mParser.Urllast != null){
			mUrl = mParser.Urllast;
			mHandler.obtainMessage(Voz.MSG_PAGE3).sendToTarget();
		}else{
			Toast.makeText(mActivity, "Cannot go to Last", Toast.LENGTH_LONG).show();
		}
	}
	OnClickListener mLoginClick = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			AlertDialog.Builder alert;
		    final View textEntryView;
		    LayoutInflater factory;
		    factory = LayoutInflater.from(mContext);
		    textEntryView = factory.inflate(R.layout.login, null);    
		    final EditText edit1 = (EditText)textEntryView.findViewById(R.id.alert_edit1);
		    final EditText edit2 = (EditText)textEntryView.findViewById(R.id.alert_edit2);
		    final TextView text1 = (TextView)textEntryView.findViewById(R.id.alert_txt1);
		    final TextView text2 = (TextView)textEntryView.findViewById(R.id.alert_txt2);
		    alert = new AlertDialog.Builder(mContext);
		    alert.setView(textEntryView);
		    if(mParser.mUserInfo().isLogin() != true){
			    alert.setTitle("Log in" );
			    text1.setVisibility(View.VISIBLE);
			    text2.setVisibility(View.VISIBLE);
			    edit1.setVisibility(View.VISIBLE);
			    edit2.setVisibility(View.VISIBLE);
			    text1.setText("Username:");
			    text2.setText("Password:");

		    }else{
		    	alert.setTitle("Log out" );
			    text1.setVisibility(View.GONE);
			    text2.setVisibility(View.GONE);
			    edit1.setVisibility(View.GONE);
			    edit2.setVisibility(View.GONE);
		    }
		    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		    	public void onClick(DialogInterface dialog, int whichButton) {
		    		if(mParser.mUserInfo().isLogin() != true){
			    		mUser.add(edit1.getText().toString(), edit2.getText().toString());
			    		//mUser.add("17up", "123654");
			    		mHandler.obtainMessage(Voz.MSG_LOGIN,mUrl).sendToTarget();
		    		}else{
		    			mHandler.obtainMessage(Voz.MSG_LOGOUT,mUrl).sendToTarget();
		    		}
		    	}
		    });
		    alert.show();
		}
	};
	
	private void alertDialog(){
	    factory = LayoutInflater.from(mContext);
	    textEntryView = factory.inflate(R.layout.login, null);    
	    edit1 = (EditText)textEntryView.findViewById(R.id.alert_edit1);
	    edit2 = (EditText)textEntryView.findViewById(R.id.alert_edit2);
	    text1 = (TextView)textEntryView.findViewById(R.id.alert_txt1);
	    text2 = (TextView)textEntryView.findViewById(R.id.alert_txt2);
	    alert = new AlertDialog.Builder(mContext);
	    alert.setView(textEntryView);
    }
	private void alertDialogDisconnect(){
    	edit1.setVisibility(View.GONE);
    	edit2.setVisibility(View.GONE);
    	text2.setVisibility(View.GONE);
    	text1.setText("Error Connection");
    }
	private void alertDialogLogin(){
    	edit1.setVisibility(View.GONE);
    	edit2.setVisibility(View.GONE);
    	text2.setVisibility(View.GONE);
    	text1.setText("Invalid username or password");
	}
	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		for(int i=0;i<taskLoadImg.size();i++){
			taskLoadImg.get(i).ld.cancel(true);
		}
		mTask.cancel(true);
	}
	private class PaserTask extends AsyncTask<Integer, Void, Integer>{

		@Override
		protected Integer doInBackground(Integer... params) {
			// TODO Auto-generated method stub
			switch (params[0]) {
			case Voz.PASER_PASER:
				stateConenct = mParser.parser();
				break;
			case Voz.PASER_LOGIN:
				stateConenct = mParser.Login(mUser);
				break;	
			case Voz.PASER_LOGOUT:
				stateConenct = mParser.Logout();
				break;
			case Voz.PASER_QUICKREPLY:
				stateConenct = mParser.PostQuickReply(mTextReply);
				break;
			case Voz.PASER_QUOTEREPLY:
				stateConenct = mParser.PostQuoteReply(mTextReply);
				mParser.resetMultiQuote();
				break;
			case Voz.PASER_EDITREPLY:
				stateConenct = mParser.PostEdit(mTextReply);
				break;	
			case Voz.PASER_QUOTEGET:
				stateConenct = mParser.QuoteGet(params[1],params[2]);
				if(stateConenct == 0){
					if(params[2] == 0)
						mHandler.obtainMessage(Voz.MSG_CLICKQUOTE, mParser.getTextQuote()).sendToTarget();
					else 
						mHandler.obtainMessage(Voz.MSG_CLICKEDIT, mParser.getTextQuote()).sendToTarget();
				}
				break;
			case Voz.PASER_SUBSCRIBE:
				if(mUrl.contains("t=")){
					
					if(mParser.Subscribe() != true) mParser.Subscribe(mUrl.split("t=")[1]);
					else mParser.UnSubscribe(mUrl.split("t=")[1]);
					
				}
				
				break;
			default:
				break;
			}
			return params[0];
		}
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progressDialog.show();
			taskLoadImg = new ArrayList<taskLoadImage>();
			
		}
		@Override
		protected void onPostExecute(Integer result) {
			// TODO Auto-generated method stub
     		progressDialog.dismiss();
			switch (stateConenct) {
			case 0:
				switch (result) {
				case Voz.PASER_QUICKREPLY:
				case Voz.PASER_QUOTEREPLY:	
				case Voz.PASER_EDITREPLY:
					mMainList.setSelection(mParser.getContains().size());
					break;
				default:
					break;
				}
				m_Detail.setText(mParser.getIndexPage());
				if(mParser.mUserInfo().isLogin()==true){
					m_TextLogin.setText(mParser.mUserInfo().User());
				}else m_TextLogin.setText("Log on");
				adapter.notifyDataSetChanged();
				break;
			case -1:
				alertDialog();
				alertDialogDisconnect();
				alert.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
			    	public void onClick(DialogInterface dialog, int whichButton) {
			    		mHandler.obtainMessage(0).sendToTarget();
			    	}
			    });
				alert.show();
				break;
				
			case -2:
				alertDialog();
				alertDialogLogin();
				alert.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
			    	public void onClick(DialogInterface dialog, int whichButton) {
			    		m_TextLogin.performClick();
			    	}
			    });
				alert.show();
				break;
			default:
				break;
			}
			
			LoadIcon ld;
			for(int i1=0;i1 < mParser.getContains().size();i1++){
				ld = new LoadIcon();
				taskLoadImg.add(new taskLoadImage(ld, i1, -99, 99));
			}
			for(int i1=0;i1 < mParser.getContains().size();i1++){
				for(int i3=0;i3<mParser.getContains().get(i1).image.getSize();i3++){
					String temp;
					temp = mParser.getContains().get(i1).image.getStr(i3);
					ld = new LoadIcon();
					taskLoadImg.add(new taskLoadImage(ld, i1, 0, i3));
			
					if(temp.substring(0,4).equals("http")){
						ld = new LoadIcon();
						taskLoadImg.add(new taskLoadImage(ld, i1, 0, i3));
						
					}else{
						Bitmap bitmap = taskLoadImage.DownloadImage(temp);
						mParser.getContains().get(i1).image.SetBitmap(i3, bitmap);
					}
				}
			}
			index = 0;
			if(index < taskLoadImg.size()){
				int p1,p2,p3;
				p1 = taskLoadImg.get(index).para1;
				p2 = taskLoadImg.get(index).para2;
				p3 = taskLoadImg.get(index).para3;
				taskLoadImg.get(index).ld.execute(p1,p2,p3);
				
			}
			
			switch (stateConenct) {
			case 0:
				if(mParser.mUserInfo().isLogin()==true){
					m_TextLogin.setText(mParser.mUserInfo().User());
				}else m_TextLogin.setText("Log on");
				break;
			case -1:
				alertDialog();
				alertDialogDisconnect();
				alert.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
			    	public void onClick(DialogInterface dialog, int whichButton) {
			    		mHandler.obtainMessage(0).sendToTarget();
			    	}
			    });
				alert.show();
				break;
			default:
				break;
			}
		}
     }

	 public class LoadIcon extends AsyncTask<Integer, Void, Void>{
		@Override
		protected Void doInBackground(Integer... params) {
			// TODO Auto-generated method stub
			
			Bitmap bitmap = null;
			if(params[1] == -99){
				bitmap = taskLoadImage.DownloadImage(mParser.getContains(params[0]).UrlAvatar());
				mParser.getContains(params[0]).setAvatar(bitmap);
			}else{
				
				String temp = mParser.getContains(params[0]).image.getStr(params[2]);
				bitmap = taskLoadImage.DownloadImage(temp);
				mParser.getContains(params[0]).image.SetBitmap(params[2], bitmap);
			}
			return null;
		}
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			adapter.notifyDataSetChanged();
			index += 1;
			
			if(index < taskLoadImg.size()){
				int p1,p2,p3;
				p1 = taskLoadImg.get(index).para1;
				p2 = taskLoadImg.get(index).para2;
				p3 = taskLoadImg.get(index).para3;
				taskLoadImg.get(index).ld.execute(p1,p2,p3);
			}
		}
	 }

}
